package com.subsequent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.subsequent.pojo.Departments;
import com.subsequent.pojo.Doctors;
import com.subsequent.service.DepartmentsService;
import com.subsequent.service.DoctorsService;
import com.subsequent.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/departments")
public class DepartmentsController {

    @Autowired
    private DepartmentsService departmentsService;
    @Autowired
    private DoctorsService doctorsService;

    // 分页+条件查询
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer campusId,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String deptName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime
    ) {
        Page<Departments> departmentsPage = departmentsService.pageQuery(pageNum, pageSize, campusId, categoryId, deptName, status, startTime, endTime);
        return Result.success(departmentsPage);
    }

    // 树结构查询
    @GetMapping("/tree")
    public Result tree(
            @RequestParam(required = false) Integer campusId,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime
    ) {
        List<Departments> tree = departmentsService.tree(campusId, categoryId, status, startTime, endTime);
        return Result.success(tree);
    }

    // 新增科室
    @PostMapping("/add")
    public String addDepartment(@RequestBody Departments department) {
        // 检查必填字段
        if (department.getCampusId() == null || department.getCategoryId() == null || 
            department.getDeptName() == null || department.getDeptName().trim().isEmpty()) {
            return "fail: 缺少必填字段";
        }

        // 检查科室名称是否已存在
        LambdaQueryWrapper<Departments> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Departments::getDeptName, department.getDeptName());
        if (departmentsService.count(wrapper) > 0) {
            return "fail: 科室名称已存在";
        }

        // 设置创建时间和更新时间
        Date now = new Date();
        department.setCreatedAt(now);
        department.setUpdatedAt(now);
        
        // 设置默认状态为启用
        if (department.getStatus() == null) {
            department.setStatus(1);
        }
        
        // 设置默认非特色科室
        if (department.getFeatured() == null) {
            department.setFeatured(0);
        }

        // 生成科室编码（如果未提供）
        if (department.getDeptCode() == null || department.getDeptCode().trim().isEmpty()) {
            department.setDeptCode(generateDeptCode(department.getDeptName()));
        }
        
        boolean result = departmentsService.save(department);
        return result ? "success" : "fail";
    }

    // 修改科室
    @PutMapping("/edit")
    public String editDepartment(@RequestBody Departments department) {
        // 检查必填字段
        if (department.getDeptId() == null || department.getCampusId() == null || 
            department.getCategoryId() == null || department.getDeptName() == null || 
            department.getDeptName().trim().isEmpty()) {
            return "fail: 缺少必填字段";
        }

        // 检查科室名称是否已存在（排除自身）
        LambdaQueryWrapper<Departments> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Departments::getDeptName, department.getDeptName())
               .ne(Departments::getDeptId, department.getDeptId());
        if (departmentsService.count(wrapper) > 0) {
            return "fail: 科室名称已存在";
        }

        department.setUpdatedAt(new Date());
        boolean result = departmentsService.updateById(department);
        return result ? "success" : "fail";
    }

    // 删除科室
    @DeleteMapping("/delete/{id}")
    public String deleteDepartment(@PathVariable Integer id) {
        // 检查科室是否有关联的医生
        LambdaQueryWrapper<Doctors> doctorWrapper = new LambdaQueryWrapper<>();
        doctorWrapper.eq(Doctors::getDeptId, id);
        if (doctorsService.count(doctorWrapper) > 0) {
            return "fail: 该科室下存在医生，无法删除";
        }
        
        boolean result = departmentsService.removeById(id);
        return result ? "success" : "fail";
    }

    // 生成科室编码
    private String generateDeptCode(String deptName) {
        // 取科室名称的拼音首字母，如果没有则取前两个汉字
        String code = "";
        if (deptName != null && !deptName.isEmpty()) {
            if (deptName.length() >= 2) {
                code = deptName.substring(0, 2);
            } else {
                code = deptName;
            }
        }
        return code;
    }
}